﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo.Istek;
using ConfExpert.Properties;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class Istekler : XForm
    {
        public Istekler()
        {
            InitializeComponent();
        }

        public Istekler(bool isOnay)
            : this()
        {
            IsOnay = isOnay;
        }

        BindingSource bs1, bs2, bs3;
        bool IsOnay = false;
        private void Istekler_Load(object sender, EventArgs e)
        {
            this.Text = IsOnay ? "Onayımı Bekleyen İstekler" : "İsteklerim";

            bs1 = gvIstek.Init("GetIstek", IsOnay, WhoAmI);

            bs2 = gvIstek.AddDetailGrid(gvArtikel, "IstekId");
            bs3 = gvArtikel.AddDetailGrid(gvTop, "IstekId,ProductId");

            gvArtikel.AddColumn("Qty", typeof(decimal), "SUM(Child({FK}).QtySelected)");

            gvTop.AddColumn("O", typeof(int), "IIF(Onay=1, 1, 0)");
            gvTop.AddColumn("R", typeof(int), "IIF(Onay=0, 1, 0)");
            gvTop.AddColumn("I", typeof(int), "IIF(Onay is null, 1, 0)");
            gvArtikel.AddColumn("O", typeof(int), "SUM(Child({FK}).O)");
            gvArtikel.AddColumn("R", typeof(int), "SUM(Child({FK}).R)");
            gvArtikel.AddColumn("I", typeof(int), "SUM(Child({FK}).I)");
            gvIstek.AddColumn("O", typeof(int), "SUM(Child({FK}).O)");
            gvIstek.AddColumn("R", typeof(int), "SUM(Child({FK}).R)");
            gvIstek.AddColumn("I", typeof(int), "SUM(Child({FK}).I)");

            gvIstek.SetCaptions("BrandId:Nereye?");


            gvIstek.Columns["O"].ToolTip = "Onay";
            gvIstek.Columns["R"].ToolTip = "Red";
            gvIstek.Columns["I"].ToolTip = "İstek";
            gvTop.MakeColumnInvisible("O", "R", "I");
            gvIstek.FormatAsNumber(0, "O", "R", "I");
            gvArtikel.FormatAsNumber(0, "O", "R", "I");

            if (IsOnay)
            {
                GridManager gm;
                gm = GridManager.GetManager(gvTop);
                gm.GridMenu.AddMenu("Onay", TopuSec, Resources.accept_16);
                gm.GridMenu.AddMenu("Red", TopuBirak, Resources.delete_16);

                gm = GridManager.GetManager(gvArtikel);
                gm.GridMenu.AddMenu("Onay", ArtikeliSec, Resources.accept_16);
                gm.GridMenu.AddMenu("Red", ArtikeliBirak, Resources.delete_16);

                gm = GridManager.GetManager(gvIstek);
                gm.GridMenu.AddMenu("Onay", IstegiSec, Resources.accept_16);
                gm.GridMenu.AddMenu("Red", IstegiBirak, Resources.delete_16);

                if (ytk(150))
                    gvIstek.MakeReadOnly("SezonId", "OrderRef");
                else
                    gvIstek.MakeReadOnly();
                btnKaydet.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                btnKaydet.ItemClick += btnKaydet_ItemClick;
            }
            else
                gvIstek.MakeReadOnly();

            splitContainerControl.AutoSize();
            splitContainerControl2.AutoSize();

            //ds.d.Tables[2].Columns.Add("SelectedQty", typeof(decimal), "Iif(ISNULL(QtySelected,0)=0, Qty, ISNULL(QtySelected,0))");
            //gvIstek.OptionsSelection.MultiSelectMode = gvArtikel.OptionsSelection.MultiSelectMode = gvTop.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            //gvIstek.Appearance.FocusedCell.BackColor = Color.YellowGreen;

            gvArtikel.MakeReadOnly();
            gvTop.MakeReadOnly("QtyRevised");

            gvArtikel.FormatAsNumber(1, "Qty", "IDLEQty");
            gvTop.FormatAsNumber(1, "Qty", "QtySelected", "QtyRevised");

            gvIstek.MakeColumnInvisible("IDLE", "isRezerve", "RzvTill", "RzvFor", "WebRezerveId");

            gvArtikel.MakeColumnInvisible("IstekId");
            gvArtikel.Columns["IDLEQty"].VisibleIndex = IsOnay ? gvArtikel.Columns["Qty"].VisibleIndex + 1 : -1;

            gvTop.MakeColumnInvisible("Onay", "GelisPartisiId");

            btnGuncelle.ItemClick += btnGuncelle_ItemClick;
            //gvTop.RowCellClick += new DevExpress.XtraGrid.Views.Grid.RowCellClickEventHandler(gvTop_RowCellClick);

            gvTop.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gvTop_RowStyle);
            gvIstek.RowCellStyle += new RowCellStyleEventHandler(gvIstek_RowCellStyle);
            gvArtikel.RowCellStyle += new RowCellStyleEventHandler(gvIstek_RowCellStyle);
            gvArtikel.AddSummary("Qty", "IDLEQty");
            gvIstek.AddSummary();

            gvTop.OptionsView.EnableAppearanceEvenRow =
            gvTop.OptionsView.EnableAppearanceOddRow = false;
            //gvTop.Appearance.OddRow.BackColor = Color.WhiteSmoke;

            gvIstek.FocusedRowChanged += gvIstek_FocusedRowChanged;
            gvIstek_FocusedRowChanged(null, null);
            gvIstek.BestFitColumns();
        }

        void gvIstek_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //if (gvIstek.GetFocusedRowCellDisplayText("BrandId").StartsWith("ATIL D"))
            //    gvTop.YanYanaGetir_Soluna("BrandId", "Sebebi", "SonDurum", "FaturaEdilecekMi");
            //else
            //    gvTop.MakeColumnInvisible("Sebebi", "SonDurum", "FaturaEdilecekMi");

            txtInfo.Caption = "İstek: " + bs1.GetCurrentValue("IstekId");
            gvArtikel.BestFitColumns();
            gvTop.BestFitColumns();
        }

        void gvIstek_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.Column.FieldName == "O" ||
                    e.Column.FieldName == "R")
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);

        }

        void gvTop_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
            {
                object cellValue = view.GetRowCellValue(e.RowHandle, "Onay");
                if (cellValue != null && cellValue != DBNull.Value)
                {
                    if ((bool)cellValue == true)
                        e.Appearance.BackColor = Color.YellowGreen;
                    else
                        e.Appearance.BackColor = Color.OrangeRed;
                }
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);
            }
        }

        int IstekId = 0;

        /*
        void gvTop_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Onay")
            {
                bool currentStatus = false;
                if (e.CellValue != DBNull.Value)
                {
                    currentStatus = (bool)e.CellValue;
                }
                gvTop.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
            }
        }
        */



        void btnGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvIstek.RefreshDataSource("GetIstek", IsOnay, WhoAmI);
        }

        DataRow[] GetTopP(int IstekId, int ProductId)
        {
            return gvTop.DataTable().Select(string.Format("IstekId= {0} AND ProductId = {1}", IstekId, ProductId));
        }

        DataRow[] GetTopI(int IstekId)
        {
            return gvTop.DataTable().Select(string.Format("IstekId= {0}", IstekId));
        }


        void IstegiSec(object sender, EventArgs e)
        {
            if (gvIstek.SelectedRowsCount < 1)
                gvIstek.SelectRow(gvIstek.FocusedRowHandle);

            foreach (int handle in gvIstek.GetSelectedRows())
            {
                IstekId = gvIstek.GetRowCellValue(handle, "IstekId").ToInt(-1);
                foreach (DataRow row in GetTopI(IstekId))
                    row["Onay"] = true;
            }
        }

        void IstegiBirak(object sender, EventArgs e)
        {
            if (gvIstek.SelectedRowsCount < 1)
                gvIstek.SelectRow(gvIstek.FocusedRowHandle);

            foreach (int handle in gvIstek.GetSelectedRows())
            {
                IstekId = gvIstek.GetRowCellValue(handle, "IstekId").ToInt(-1);
                foreach (DataRow row in GetTopI(IstekId))
                    row["Onay"] = false;
            }
        }

        void ArtikeliSec(object sender, EventArgs e)
        {
            if (gvArtikel.SelectedRowsCount < 1)
                gvArtikel.SelectRow(gvArtikel.FocusedRowHandle);

            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                IstekId = gvArtikel.GetRowCellValue(handle, "IstekId").ToInt(-1);
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt(-1);
                foreach (DataRow row in GetTopP(IstekId, ProductId))
                    row["Onay"] = true;
            }
        }

        void ArtikeliBirak(object sender, EventArgs e)
        {
            if (gvArtikel.SelectedRowsCount < 1)
                gvArtikel.SelectRow(gvArtikel.FocusedRowHandle);

            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                IstekId = gvArtikel.GetRowCellValue(handle, "IstekId").ToInt(-1);
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt(-1);
                foreach (DataRow row in GetTopP(IstekId, ProductId))
                    row["Onay"] = false;
            }
        }

        void TopuSec(object sender, EventArgs e)
        {
            if (gvTop.SelectedRowsCount < 1)
                gvTop.SelectRow(gvTop.FocusedRowHandle);

            foreach (int handle in gvTop.GetSelectedRows())
                gvTop.SetRowCellValue(handle, "Onay", true); 
        }

        void TopuBirak(object sender, EventArgs e)
        {
            if (gvTop.SelectedRowsCount < 1)
                gvTop.SelectRow(gvTop.FocusedRowHandle);

            foreach (int handle in gvTop.GetSelectedRows())
                gvTop.SetRowCellValue(handle, "Onay", false);
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvIstek.ChangeExpression("O", string.Empty);
            gvIstek.ChangeExpression("R", string.Empty);
            gvIstek.ChangeExpression("I", string.Empty);

            int ra = gvIstek.Update("", "Istek").Rows.Count;
            if (ra > 0)
                Notify(string.Format("{0} satır güncellendi.", ra));

            gvIstek.ChangeExpression("O", "SUM(Child({FK}).O)");
            gvIstek.ChangeExpression("R", "SUM(Child({FK}).R)");
            gvIstek.ChangeExpression("I", "SUM(Child({FK}).I)");
            gvIstek.FormatAsNumber(0, "O", "R", "I");
            gvIstek.AddSummary();

            bs1.EndEdit();
            bs2.EndEdit();
            bs3.EndEdit();

            DataTable dt = gvTop.DataTable().Clone();
            dt.TableName = "Istekler";

            foreach (DataRow dr in gvTop.DataTable().Select("Onay is not null"))
                dt.ImportRow(dr);

            if (dt.Rows.Count > 0)
            {
                //splitContainerControl.Enabled = false;
                
                DataTable dtPopUp = ExecuteDataTable("GetSatisLines", dt.Serialize(), WhoAmI);

                if (dtPopUp.Rows.Count == 0)
                {
                    DataTable dti = ExecuteDataTable("IstekOnayla3", dt.Serialize(), WhoAmI, null);

                    if (isProduction)
                        foreach (DataRow dr in dti.Rows)
                        {
                            IstekId = dr["IstekId"].ToInt(-1);
                            string to = dr["Email"].ToString();
                            Mail.Send(to, "Ayrım İsteği " + IstekId.ToStr(), string.Format("{0} Id'li ayrım isteğinize cevap verilmiştir. Lütfen kontrol ediniz.", IstekId), "");
                        }
                }
                else
                {
                    using (IstekOnayi IstekOnay = new IstekOnayi(dtPopUp))
                    {
                        if (IstekOnay.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            DataTable dti = ExecuteDataTable("IstekOnayla3", dt.Serialize(), WhoAmI, IstekOnay.xmlData);

                            if (isProduction)
                                foreach (DataRow dr in dti.Rows)
                                {
                                    IstekId = dr["IstekId"].ToInt(-1);
                                    string to = dr["Email"].ToString();
                                    Mail.Send(to, "Ayrım İsteği " + IstekId.ToStr(), string.Format("{0} Id'li ayrım isteğinize cevap verilmiştir. Lütfen kontrol ediniz.", IstekId), "");
                                }
                        }
                        else
                        {
                            IstekOnay.Dispose();
                            IstekOnay.Close();
                        }
                    }
                }
            }
            //splitContainerControl.Enabled = true;
            btnGuncelle.PerformClick();
        }
    }
}